package com.pan.admin.module.api.service.impl;

import com.pan.admin.module.api.dao.ApiKeyDao;
import com.pan.admin.module.api.dao.ApiLogDao;
import com.pan.admin.module.api.entity.ApiLog;
import com.pan.admin.module.api.entity.qo.ApiLogQO;
import com.pan.admin.module.api.service.ApiLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * API日志
 *
 * @author caoxin
 */
@Service
public class ApiLogServiceImpl implements ApiLogService {

    @Autowired
    private ApiLogDao apiLogDao;
    @Autowired
    private ApiKeyDao apiKeyDao;

    /**
     * 根据ID获取列表API日志
     *
     * @param id API日志主键
     * @return API日志
     */
    @Override
    @Transactional(readOnly = true)
    public ApiLog getById(Long id) {
        return this.apiLogDao.getById(id);
    }

    /**
     * 查询API日志列表
     *
     * @param apiLogQO API日志
     * @return API日志
     */
    @Override
    @Transactional(readOnly = true)
    public List<ApiLog> list(ApiLogQO apiLogQO) {
        List<ApiLog> list = this.apiLogDao.list(apiLogQO);
        list.forEach(item -> {
            String apiClientId = item.getApiClientId();
            if (apiClientId == null) {
                return ;
            }
            String apiName = this.apiKeyDao.findApiNameByApiCleanId(apiClientId);
            item.setApiName(apiName);
        });
        return list;
    }

    /**
     * 清理API日志
     */
    public void clean() {
        this.apiLogDao.clean();
    }

    /**
     * 清理API日志(并发失败)
     */
    public void cleanApiLogDiscard() {
        this.apiLogDao.cleanApiLogDiscard();
    }

}
